/* eslint-disable no-unused-vars */
/* eslint-disable react/react-in-jsx-scope */
import Icon from '@/components/Icon'
import useInitState from '@/hooks/useInitState'
import { getUser } from '@/store/actions/profile'
import { getToken } from '@/utils/storage'
import { NavBar, Input, List } from 'antd-mobile'
import { useEffect, useRef, useState } from 'react'
import { useHistory } from 'react-router-dom'
import { io, Socket } from 'socket.io-client'
import styles from './index.module.scss'

const Chat = () => {
  // 用于操作聊天列表元素的引用
  const chatListRef = useRef<HTMLDivElement>(null)
  // 用于缓存 socket.io 客户端实例
  const clientRef = useRef<Socket | null>(null)
  const [message, setMessage] = useState('')
  const send = () => {
    if (!message) {
      return
    }
    // 1.发消息
    clientRef.current?.emit('message', { msg: message, timestamp: Date.now() })
    // 2.把消息添加到页面上
    setMessageList((messageList) => [...messageList, { type: 'user', message }])
  }
  useEffect(() => {
    // 建立连接
    // const client = io('http://toutiao.itheima.net', {
    const url = 'http://toutiao.itheima.net'
    // const url = 'http://localhost:3000'
    const client = io(url, {
      transports: ['websocket'],
      // 在查询字符串参数中传递 token
      query: {
        token: getToken().token
      }
    })
    // console.log(client)
    client.on('connect', () => {
      console.log('当和服务器建立连接成功，这个事件就会触发')
      // 主动给服务器发送消息
      // client.emit('message', { msg: 'ceshi', timestamp: Date.now() })
      client.on('message', (data) => {
        console.log('从服务器来的消息', data)
        // 把消息添加到页面上
        setMessageList((messageList) => [...messageList, { type: 'robot', message: data.msg }])
      })
    })
    clientRef.current = client
  }, [])
  const history = useHistory()
  // 当前用户信息
  const { user: userInfo } = useInitState(getUser, 'profile')
  console.log(userInfo)
  const [messageList, setMessageList] = useState<{type: 'robot' | 'user', message: string}[]>([
    { type: 'robot', message: '我是机器人' },
    { type: 'user', message: '我是用户' }])
  // 当聊天内容变化后，设置滚动条位置，让它滚动到最底部
  useEffect(() => {
    // 设置scrollTop
    const dom = chatListRef.current
    if (dom) {
      dom.scrollTop = dom?.scrollHeight
    }
  }, [messageList])
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar className="fixed-header" onBack={() => history.go(-1)}>
        小智同学
      </NavBar>

      {/* 聊天记录列表 */}
      <div className="chat-list" ref={chatListRef}>
        {messageList.map((it, idx) => {
          return it.type === 'robot'
            ? (
                <div key={idx} className="chat-item">
                    <Icon type="iconbtn_xiaozhitongxue" />
                    <div className="message">{it.message}</div>
                </div>
              )
            : (
                <div key={idx} className="chat-item user">
                    <img src={userInfo.photo} alt="" />
                    <div className="message">{it.message}</div>
                </div>
              )
        })}
      </div>

      {/* 底部消息输入框 */}
      <div className="input-footer">
        <List.Item
          className="login-code-extra"
          extra={<span className="code-extra" onClick={send}>发送</span>}>
          <Input onChange={val => setMessage(val)} value={message} className="no-border" placeholder="请描述您的问题" />
        </List.Item>
        <Icon type="iconbianji" />
      </div>
    </div>
  )
}

export default Chat
